<script setup>
defineOptions({
  name: 'SidebarMenu',
});
import { ref, computed } from 'vue';
import { useUserStore, useThemeStore } from '@/stores';
import { useRouter, useRoute } from 'vue-router';
import MenuItem from './MenuItem.vue';

const userStore = useUserStore();
const themeStore = useThemeStore();

const router = useRouter();
const route = useRoute();

const selectedKeys = ref([]);

// 从store获取菜单和用户数据
const menuItems = computed(() => {
  const menus = userStore.getMenuTree || [];
  // // 过滤掉根路径/的菜单项，只显示实际的菜单
  // return menus.map((item) => {
  //   if (item.path !== '/') {
  //     return item;
  //   }
  //   return item.children?.[0] || item;
  // });
  return menus
});

watch(
  () => route.path,
  (newPath) => {
    selectedKeys.value = [newPath];
  },
  { immediate: true },
);

const handleMenuClick = ({ key }) => {
  router.push(key);
};

const navMode = computed(() => {
  if (themeStore.layoutSetting.layout === 'vertical') {
    return 'horizontal';
  } else if (themeStore.layoutSetting.layout === 'horizontal') {
    return themeStore.layoutSetting.inline ? 'inline' : 'vertical';
  }
});
</script>

<template>
  <a-menu
    class="menu"
    :selectedKeys="selectedKeys"
    :mode="navMode"
    triggerSubMenuAction="hover"
    @click="handleMenuClick"
  >
    <template v-for="item in menuItems" :key="item.path">
      <MenuItem :menu-item="item" />
    </template>
  </a-menu>
</template>
